<?php
require_once dirname(__FILE__) . '/FBLoginModel.php';
require_once dirname(__FILE__) . '/FBLoginView.php';
require_once dirname(__FILE__) . '/../users/UsersView.php';
require_once dirname(__FILE__) . '/../users/UsersModel.php';
require_once dirname(__FILE__) . '/../common/Database.php';
require_once dirname(__FILE__) . '/../common/DBConfig.php';
require_once dirname(__FILE__) . '/../common/IController.php';
require_once dirname(__FILE__) . '/../facebook/src/facebook.php';
require_once dirname(__FILE__) . '/../event/EventController.php';

class FBLoginController implements IController {
	private $loginModel;
	private $usersModel;

	public function __construct(FBLoginModel $lm, UsersModel $um) {
		$this->loginModel = $lm;
		$this->usersModel = $um;
	}

	/**
	* Sköter om enloggning m.h.a. facebook
	*
	* @return String HTML
	*/
	public function doControl() {
		$html = '';
		$fblv = new FBLoginView();
		$uv = new UsersView();
		
		if ($fblv->triedToLogout()) {
			$this->loginModel->logout();
			$fblv->ReloadPage();
		}
		
		$user = $this->loginModel->getLoggedInUserFromFb();
		
		if ($uv->triedToRegister()) {		
			$user->email = $uv->getEmail();
			$user->house = $uv->getHouse();
			$user->role = UsersModel::NOT_CONFIRMED_ROLE;
			
			$this->usersModel->addUser($user);
		}
		
		$html .= $fblv->getLoginButton();

		if ($this->loginModel->isLoggedIn()) {
			
			if (!$this->loginModel->isRegistered()) {
				$html .= $uv->getRegistrationForm();
			}
		}

		return $html;
	}
}
